package com.pan.download4.ctrl;

import com.pan.download4.tool.WriteChapter;
import com.pan.entity.Chapter;

import java.util.HashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

public class WriteChapterSynchronized {

    private Integer chapterId;
    private WriteChapter writeChapter;
    private HashMap<Integer,Thread> waitChapterThreadMap;
    private ReentrantLock writeLock;
    private ReentrantLock mapLock;


    public WriteChapterSynchronized(String dirPath,String bookName){
        chapterId = -1;
        writeChapter = new WriteChapter(dirPath, bookName);
        writeLock = new ReentrantLock();
        mapLock = new ReentrantLock();
        waitChapterThreadMap = new HashMap();
    }

    public void block(Integer writeChapterId){
        mapLock.lock();
        waitChapterThreadMap.put(writeChapterId,Thread.currentThread());
        mapLock.unlock();
        LockSupport.park();
    }

    public void wakeUp(Integer writeChapterId){
        mapLock.lock();
        if (waitChapterThreadMap.containsKey(writeChapterId)){
            LockSupport.unpark(waitChapterThreadMap.get(writeChapterId));
            waitChapterThreadMap.remove(writeChapterId);
        }
        mapLock.unlock();
    }




    public void write(Chapter chapter, String content){
       for (;;) {
           writeLock.lock();
           int writeChapterId = chapter.getOrderNumber();
           String title = chapter.getTitle();
           if (writeChapterId == chapterId + 1) {
               chapterId = writeChapterId;
               writeChapter.append(content);// "\n\n\n\n\n\n"+title+"\n\n\n\n\n"
               wakeUp(writeChapterId + 1);
               writeLock.unlock();
               break;
           } else {
               writeLock.unlock();
               block(writeChapterId);
           }
       }
    }
    public void close(){
        writeChapter.close();
    }
}
